﻿@using Microsoft.Extensions.Localization
@using Project.Constraints.Page
@using System.Linq.Expressions
@using Project.Constraints.UI.Table
@using Project.Web.Shared.Utils
@namespace Project.Web.Shared.Components
@typeparam TData
@inherits BasicComponent
<div style="text-align:right;margin-bottom:10px;">
    @UI.BuildButton(this).Text(TableLocalizer["TableButtons.AddCondition"].Value).OnClick(AddCondition).SetButtonType(ButtonType.Primary).Render()
</div>
@for (var i = 0; i < Conditions.Count; i++)
{
    int index = i;
    @* <ConditionBuilder Localizer="Localizer" TableLocalizer=TableLocalizer Index=index Columns=Columns InfoChanged=@(newInfo => Conditions[index] = newInfo) Style="width:100%;"></ConditionBuilder> *@
}
<div style="text-align:right;margin-top:10px;">
    @UI.BuildButton(this).Text(TableLocalizer["TableButtons.Query"].Value).OnClick(ConfirmConditionToSearch).SetButtonType(ButtonType.Primary).Render()
    @if (ShowExportButton)
    {
        @UI.BuildButton(this).Text(TableLocalizer["TableButtons.Export"].Value).OnClick(ConfirmConditionToExport).SetButtonType(ButtonType.Primary).Render()
    }
</div>
@code {
    [Parameter, NotNull]
    public List<ColumnInfo>? Columns { get; set; }
    [Parameter]
    public Expression<Func<TData, bool>>? Expression { get; set; }
    [Parameter]
    public EventCallback<Expression<Func<TData, bool>>> ExpressionChanged { get; set; }
    [Parameter]
    public bool ShowExportButton { get; set; }
    [Parameter]
    public EventCallback OnConfirmToSearch { get; set; }
    [Parameter]
    public EventCallback OnConfirmToExport { get; set; }
    [Parameter, NotNull] 
    public IStringLocalizer? Localizer { get; set; }
    [Parameter, NotNull] 
    public IStringLocalizer? TableLocalizer { get; set; }
    private List<ConditionInfo> Conditions = new List<ConditionInfo>();
    protected override void OnInitialized()
    {
        base.OnInitialized();
        Conditions.Add(new ConditionInfo("", CompareType.Equal, "", typeof(string), false));
    }
    void AddCondition()
    {
        var condition = new ConditionInfo("", CompareType.Equal, "", typeof(string), false);
        Conditions.Add(condition);
    }
    public async Task ConfirmConditionToSearch()
    {
        var exp = BuildCondition.CombineExpression<TData>(new Queue<ConditionInfo>(Conditions));
        await ExpressionChanged.InvokeAsync(exp);
        _ = OnConfirmToSearch.InvokeAsync();
    }

    public async Task ConfirmConditionToExport()
    {
        var exp = BuildCondition.CombineExpression<TData>(new Queue<ConditionInfo>(Conditions));
        await ExpressionChanged.InvokeAsync(exp);
        _ = OnConfirmToExport.InvokeAsync();
    }

}
